<template>
  <view class="page-container">
    <!-- uni-forms 组件用于创建表单 -->
    <uni-forms ref="form" :modelValue="formData" :rules="rules" label-width="80px" label-align="right">
      <!-- 基本信息卡片 -->
      <view class="form-section">
        <view class="section-title">基本信息</view>
        <uni-forms-item label="姓名" name="name" required>
          <uni-easyinput v-model="formData.name" placeholder="请输入姓名" />
        </uni-forms-item>
        <uni-forms-item label="身份证号" name="idCard">
          <uni-easyinput v-model="formData.idCard" placeholder="请输入身份证号" />
        </uni-forms-item>
        <uni-forms-item label="性别" name="gender">
          <uni-data-checkbox v-model="formData.gender" :localdata="genderRange"></uni-data-checkbox>
        </uni-forms-item>
        <uni-forms-item label="出生日期" name="dateOfBirth">
          <uni-datetime-picker type="date" :value="formData.dateOfBirth"
                               @change="dateChange" />
        </uni-forms-item>
        <uni-forms-item label="现居地址" name="currentAddress">
          <uni-easyinput type="textarea" v-model="formData.currentAddress" placeholder="请输入详细地址" />
        </uni-forms-item>
      </view>

      <!-- 详细信息卡片 -->
      <view class="form-section">
        <view class="section-title">详细信息</view>
        <uni-forms-item label="籍贯" name="birthplace">
          <uni-easyinput v-model="formData.birthplace" placeholder="请输入籍贯" />
        </uni-forms-item>
        <uni-forms-item label="民族" name="ethnicity">
          <uni-easyinput v-model="formData.ethnicity" placeholder="请输入民族" />
        </uni-forms-item>
        <uni-forms-item label="文化程度" name="educationLevel">
          <picker mode="selector" :range="educationRange" :value="educationIndex" @change="educationChange">
            <view class="picker-view">{{ formData.educationLevel || '请选择' }}</view>
          </picker>
        </uni-forms-item>
        <uni-forms-item label="婚姻状况" name="maritalStatus">
          <picker mode="selector" :range="maritalRange" :value="maritalIndex" @change="maritalChange">
            <view class="picker-view">{{ formData.maritalStatus || '请选择' }}</view>
          </picker>
        </uni-forms-item>
        <uni-forms-item label="职业" name="occupation">
          <uni-easyinput v-model="formData.occupation" placeholder="请输入职业" />
        </uni-forms-item>
        <uni-forms-item label="工作单位" name="workUnit">
          <uni-easyinput v-model="formData.workUnit" placeholder="请输入工作单位" />
        </uni-forms-item>
      </view>

    </uni-forms>

    <!-- 页面底部的提交按钮 -->
    <view class="submit-button-container">
      <button class="submit-button" type="primary" @click="submitForm">保存信息</button>
    </view>
  </view>
</template>

<script>
import { mapState } from 'vuex';
import UniEasyinput from "../../../uni_modules/uni-easyinput/components/uni-easyinput/uni-easyinput.vue";
import UniFormsItem from "../../../uni_modules/uni-forms/components/uni-forms-item/uni-forms-item.vue";
import UniDatetimePicker from "../../../uni_modules/uni-datetime-picker/components/uni-datetime-picker/time-picker.vue";
import UniForms from "../../../uni_modules/uni-forms/components/uni-forms/uni-forms.vue";
import { updateInfo} from "../../../api/resident";

export default {
  name: "edit-detail",
  components: {UniForms, UniDatetimePicker, UniFormsItem, UniEasyinput},
  data() {
    return {
      // 表单数据对象，初始为空，将由 store 填充
      formData: {},
      // 性别选项
      genderRange: [{ text: '男', value: '男' }, { text: '女', value: '女' }],
      // 文化程度选项
      educationRange: ['小学', '初中', '高中', '大专', '本科', '硕士', '博士'],
      // 婚姻状况选项
      maritalRange: ['未婚', '已婚', '离异', '丧偶'],
      // 表单校验规则
      rules: {
        residentName: {
          rules: [{ required: true, errorMessage: '姓名为必填项' }]
        }
      }
    };
  },
  computed: {
    // 从 store 的 state 中映射 userInfo 到名为 user 的计算属性
    ...mapState({
      user: state => state.userInfo
    }),
    // 计算 picker 的当前选中索引，用于正确回显
    educationIndex() {
      return this.educationRange.indexOf(this.formData.educationLevel);
    },
    maritalIndex() {
      return this.maritalRange.indexOf(this.formData.maritalStatus);
    }
  },
  // 页面加载时触发
  onLoad() {
    // 直接从 store 中加载当前登录用户的数据来填充表单
    this.loadData();
  },
  methods: {
    // 从 store 加载数据到表单
    async loadData() {
      this.formData = { ...this.user };
      console.log("已从 Store 加载用户信息:", this.formData);
    },
    // 日期选择器值改变时触发
    dateChange(date) {
      this.formData.dateOfBirth = date;
    },
    // 文化程度选择器值改变时触发
    educationChange(e) {
      const index = e.detail.value;
      this.formData.educationLevel = this.educationRange[index];
    },
    // 婚姻状况选择器值改变时触发
    maritalChange(e) {
      const index = e.detail.value;
      this.formData.maritalStatus = this.maritalRange[index];
    },
    // 点击保存按钮，提交表单
    async submitForm() {
      // 1. 设置加载状态，防止用户重复提交
      this.isLoading = true;
      try {
        // 2. 使用 const 和更简洁的解构赋值
        const { data } = await updateInfo(this.formData);
        // 3. 根据 code 判断操作是否成功
        if (data.code === 200) {
          // 4. 给予用户清晰的成功提示
          uni.showToast({
            title: '修改成功！',
            icon: 'success'
          });
          const updateUserInfo = {...this.$store.state.userInfo, ...this.formData}
          this.$store.commit('setUserInfo',updateUserInfo)
          // 可以在成功后执行其他操作，例如延时返回上一页
          setTimeout(() => {
            uni.navigateBack();
          }, 1500); // 1.5秒后返回

        } else {
          // 5. 如果失败，显示后端返回的具体错误信息
          uni.showToast({
            title: data.msg || '保存失败，请稍后再试',
            icon: 'none' // icon 设置为 'none' 可以显示多行文字
          });
        }
      } catch (error) {
        // 6. 捕获请求过程中的异常（如网络问题、服务器异常等）
        console.error("更新信息失败:", error); // 在控制台打印详细错误
        uni.showToast({
          title: '网络错误，请检查您的网络连接',
          icon: 'none'
        });
      } finally {
        // 7. 无论成功或失败，最后都要结束加载状态
        this.isLoading = false;
      }
    }
  }
}
</script>

<style scoped>
.page-container {
  background-color: #f9f9f9;
  padding: 24rpx;
  padding-bottom: 160rpx; /* 为底部按钮留出更多空间 */
}

.form-section {
  background-color: #ffffff;
  border-radius: 16rpx;
  padding: 10rpx 30rpx 30rpx 30rpx;
  margin-bottom: 24rpx;
  box-shadow: 0 4rpx 20rpx rgba(0, 0, 0, 0.05);
}

.section-title {
  font-size: 32rpx;
  font-weight: bold;
  color: #333;
  padding: 30rpx 0;
  border-bottom: 1rpx solid #f0f0f0;
  margin-bottom: 20rpx;
}

.picker-view {
  height: 36px;
  line-height: 36px;
  border: 1px solid #e5e5e5;
  border-radius: 4px;
  padding: 0 10px;
  font-size: 14px;
  color: #333;
  display: flex; /* 让文字垂直居中 */
  align-items: center;
}

.submit-button-container {
  position: fixed;
  bottom: 0;
  left: 0;
  width: 100%;
  background-color: #ffffff;
  padding: 20rpx 30rpx;
  padding-bottom: calc(20rpx + constant(safe-area-inset-bottom)); /* 适配 iPhone X 等机型 */
  padding-bottom: calc(20rpx + env(safe-area-inset-bottom));
  box-shadow: 0 -2rpx 20rpx rgba(0, 0, 0, 0.08);
  box-sizing: border-box;
  display: flex; /* 新增：使用 flex 布局 */
  gap: 20rpx; /* 新增：按钮之间的间距 */
}

.cancel-button {
  flex: 1; /* 新增：占据一半空间 */
  height: 90rpx;
  line-height: 90rpx;
  border-radius: 16rpx;
  font-size: 32rpx;
  background-color: #f0f0f0;
  color: #333;
}

.cancel-button::after {
  border: none;
}

.submit-button {
  flex: 1; /* 新增：占据一半空间 */
  height: 90rpx;
  line-height: 90rpx;
  border-radius: 16rpx;
  font-size: 32rpx;
  background-color: #007aff;
}
</style>

